<template>
  <div>
    <div class="pagination">
      <button @click="$emit('currentChange', pageNo - 1)" :disabled="pageNo == 1">
        上一页
      </button>
      <button v-show="startAndEndNumber.start > 1" @click="$emit('currentChange', 1)">
        1
      </button>
      <button v-show="startAndEndNumber.start > 2">···</button>
      <!-- v-for与v-if优先级:v-for -->
      <button @click="sendPage(page)" :class="{ active: pageNo == page }"
        v-for="(page, index) in startAndEndNumber.end" v-if="page >= startAndEndNumber.start">
        {{ page }}
      </button>
      <button v-show="startAndEndNumber.end < totalPage - 1">···</button>
      <button v-show="startAndEndNumber.end < totalPage" @click="$emit('currentChange', totalPage)">
        {{ totalPage }}
      </button>
      <button @click="$emit('currentChange', pageNo + 1)" :disabled="pageNo == totalPage">
        下一页
      </button>
      <!-- 每一页展示数据条数 -->
      <select v-model="pageSizes" @change="$emit('getPageSizes',pageSizes)">
        <option v-for="item in pagerCount" :value="item">{{item}}条/页</option>
      </select>
      <button style="margin-left: 30px">共 {{ total }} 条</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Pagination',
  data() {
    return {
      pageSizes: 10,
    };
  },
  props: ['total', 'pageSize', 'pageNo', 'pager', 'pagerCount'],
  computed: {
    //计算出总共多少页
    totalPage() {
      return Math.ceil(this.total / this.pageSize);
    },
    //计算出分页器中间连续页码起始与结束的数字
    startAndEndNumber() {
      let start, end;
      //pager:中间连续页码个数 totalPage总页数
      const { pager, totalPage, pageNo } = this;
      //特殊清空:连续页码数大于总页数
      if (pager > totalPage) {
        start = 1;
        end = totalPage;
      } else {
        //正常清理:连续页码数(5|7|9)小于等于总页数
        start = pageNo - parseInt(pager / 2);
        end = pageNo + parseInt(pager / 2);
        //左侧非法情况纠正
        if (start < 1) {
          start = 1;
          end = pager;
        }
        //右侧出现非法情况
        if (end > totalPage) {
          end = totalPage;
          start = totalPage - pager + 1;
        }
      }
      return { start, end };
    },
  },
  methods: {
    //父组件传递参数:当前页码
    sendPage(page) {
      this.$emit('currentChange', page);
    },
  },
};
</script>


<style lang="less" scoped>
.pagination {
  display: flex;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>